local CheckWidgetType = UI.CheckWidgetType
local CheckArgType = UI.CheckArgType
local CheckArgWidget = UI.CheckArgWidget
local MakeAccessor = UI.MakeAccessor
local MakeTypeSetter = UI.MakeTypeSetter

--[[ ScrollFrame @FIXME ]]--
local ScrollFrame = UI.NewWidgetType("ScrollFrame", "Frame")
ScrollFrame.parameters = {
	voffset = 0,
	vrange = 0,
	hoffset = 0,
	hrange = 0,
}

function ScrollFrame:Initialize(o)
	local t = UI.params[o]
	assert(t)
end

function ScrollFrame.prototype:UpdateScrollChildRect()
	CheckWidgetType("ScrollFrame:UpdateScrollChildRect", self, "ScrollFrame")
	local t = UI.params[self]
	if not t.child then return end
	UI.Layout(t.child)
	local ct = UI.params[t.child]
	local width, height, changed = ct.rect.width, ct.rect.height, false
	if width ~= t.hrange then
		changed = true
		t.hrange = width
		if t.hoffset > width then
			t.hoffset = width
		end
	end
	if height ~= t.vrange then
		changed = true
		t.vrange = height
		if t.voffset > height then
			t.voffset = height
		end
	end
	if changed then
		UI.CallScript(self, "OnScrollRangeChanged", width, height)
	end
end

function ScrollFrame.prototype:SetScrollChild(child)
	CheckWidgetType("ScrollFrame:SetScrollChild", self, "ScrollFrame")
	CheckArgWidget("ScrollFrame:SetScrollChild", 2, "child", "Frame", child)
	UI.params[self].child = child
end

function ScrollFrame.prototype:GetScrollChild()
	CheckWidgetType("ScrollFrame:GetScrollChild", self, "ScrollFrame")
	return UI.params[self].child
end


MakeAccessor("ScrollFrame", "GetVerticalScroll", "voffset")
MakeAccessor("ScrollFrame", "GetVerticalScrollRange", "vrange")
MakeAccessor("ScrollFrame", "GetHorizontalScroll", "hoffset")
MakeAccessor("ScrollFrame", "GetHorizontalScrollRange", "hrange")

function ScrollFrame.prototype:SetHorizontalScroll(offset)
	CheckWidgetType("ScrollFrame:SetHorizontalScroll", self, "ScrollFrame")
	local t = UI.params[self]
	if offset < 0 then
		offset = 0
	elseif offset > t.hrange then
		offset = t.hrange
	end
	if t.hoffset ~= offset then
		t.hoffset = offset
		UI.CallScript(self, "OnHorizontalScroll", offset)
	end
end

function ScrollFrame.prototype:SetVerticalScroll(offset)
	CheckWidgetType("ScrollFrame:SetVerticalScroll", self, "ScrollFrame")
	local t = UI.params[self]
	if offset < 0 then
		offset = 0
	elseif offset > t.vrange then
		offset = t.vrange
	end
	if t.voffset ~= offset then
		t.voffset = offset
		UI.CallScript(self, "OnVerticalScroll", offset)
	end
end

UI.RegisterScriptHandlers(ScrollFrame, "OnScrollRangeChanged",
	"OnVerticalScroll", "OnHorizontalScroll")
